using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using DICE_GS;

public class UIManager : MonoBehaviour {
	
	private static UIManager instance;

	public static UIManager Instance{
		get{
			return instance;
		}
	}	

	void Awake()
	{
		instance = this;
		is_castable_skill = new bool[4];
		is_castable_tempSkill = new bool[2];
	}
	
	public GameObject diceNum_prefab;
	public GameObject diceNum;
	GameObject diceNumMinus;
	GameObject minusGo;
	GameObject digit2Go;
	public int nLastDice;
	//UISprite rollGaugeSprite;
	//RollGauge rollGauge;
	public DiceType diceType;
	public Transform [] gameResultRankPos;
	public GameObject gameResultMyRankMarkFrame;
	public GameObject gameResultMyRankMarkArrow;
	public GameObject [] rankName;
	
	public GameObject nickName;
	
	//public GameObject connectButton;
	//public GameObject pcButton;
	//public GameObject aiButton;
	//public GameObject orderButton;
	public GameObject rollPanel;
	public GameObject skillItemPanel;
	public RollGaugeAnimation rollGaugeAnim_moveDice;
	//public GameObject battleRollPanel;
	public GameObject gaugeRollPanel;
	public RollGaugeAnimation rollGaugeAnim;
	public UISprite rollBtnSprite;
//	public RollGauge rollGaugeL;
//	public RollGauge rollGaugeR;
//	public GameObject moveRollButton;
//	public GameObject timerSlider;
//	public GameObject battleRollButton;
	public GameObject orderButtonText;
	//public GameObject createPawnPanel;
	public GameObject gameResultUI;
	public GameObject selectRewardUI;
	public GameObject selectPathlabel;
	public GameObject [] selectPathObj;
	public GameObject [] pathSelectPrefab;
	public bool isCreatedPathSelectIndicator;
	public GameObject [] playerReadyPanel;
	public GameObject [] mainHUD;
	public GameObject [] panelRank;
	public GameObject [] rankIcon;
	
	public GameObject panelSkillBar;
	
	public bool bDisabledAllBtn;
	bool isConnectedCheck = false;
	public CPawnWrapper m_pawnWrapper;
	public bool bUseSkill;
	public bool bCreatePawnPanel;
	public GameObject centerAnchor;
	public GameObject bottomAnchor;
	public GameObject [] resultItemBox;
	Dictionary<int,int> categoryToBoxDic = new Dictionary<int, int>();
	bool [] is_castable_skill;
	bool [] is_castable_tempSkill;
	List<int> rewardPossibleBoxList = new List<int>();
	//List<int> selectedRewardList = new List<int>();
	// Use this for initialization
	
	int timeCountDice;
	//public GameObject blackBox;
	
	public Texture [] textureCount;
	public bool bHideRoll;
	public GameObject FX_CountNum_obj;
	public GameObject FX_CountNum_obj_prefab;
	PressSkillBar pressSkillBar;
	
	public GameObject gameStartPrefab;
	public GameObject gameStartNumPrefab;
	public Texture [] gameStartTexture;
	
	public GameObject debugCamPanel;
	public UIPanel blackFocus;
	
	public GameObject skillNameShowPrefab;
	public GameObject cardSkillNamePrefab;
	public int reward_gachaPoint;
	public int reward_unitCount;
	
	
	GameObject finishPopup;
	public Vector3 finishPopup_originalPos;
	
	public GameObject skillInfoTextPrefab;
	GameObject goShowSkillInfo;
	GameObject skillNameShowGo;
	GameObject cardSkillNameGo;
	Dictionary<UIType, string> uiString = new Dictionary<UIType, string>();
	Dictionary<int, string> skillNameDic = new Dictionary<int, string>();
	List<GameObject> directionDiceIcons = new List<GameObject>();

	public GameObject miniMapBar;
	public GameObject topAnchor;

	public GameObject tempRebirthButton;

	public UILabel statusBoardText;
	int nDiceProb;
	GameObject diceIcon1;
	GameObject diceIcon2;
	GameObject diceIcon3;
	public GameObject testDiceColorPanel;
	public DiceShapeType curDiceShape;

	void Start () {
		//createPawnPanel.SetActive(false);
		ShowMainHud(true);
		selectPathObj = new GameObject[4];
		
		categoryToBoxDic.Add( (int)BoxCategory.EXP, 0);
		categoryToBoxDic.Add( (int)BoxCategory.COIN, 1);
		categoryToBoxDic.Add( (int)BoxCategory.ITEM,  2);
		categoryToBoxDic.Add( (int)BoxCategory.UNIT,  3);
		categoryToBoxDic.Add( (int)BoxCategory.GACHA_POINT,  3);		
		
		pressSkillBar = panelSkillBar.GetComponent<PressSkillBar>();
		//SetHealItemCount(MyInfo.Instance.HPPotion, MyInfo.Instance.ResurrectPotion);
		
		CreateDiceNum();

		//GameObject go = rollPanel.transform.FindChild("gauge").gameObject;
		//rollGaugeSprite = go.GetComponent<UISprite>();
		//rollGauge = go.GetComponent<RollGauge>();
	}
	
	public void MakeUIEffect()
	{
		uiString.Add ( UIType.UI_DRAW_VICTORY, CStringTableManager.Instance.GetItemById(1674) );
		uiString.Add ( UIType.UI_DRAW_DEFEAT, CStringTableManager.Instance.GetItemById(1673) );
		uiString.Add ( UIType.UI_COMBAT_REMATCH, CStringTableManager.Instance.GetItemById(1688) );
		uiString.Add ( UIType.UI_COMBAT_REDICE, CStringTableManager.Instance.GetItemById(1687) );
		
		skillNameShowGo = NGUITools.AddChild(centerAnchor, skillNameShowPrefab);
		skillNameShowGo.SetActive(false);
		
		cardSkillNameGo = NGUITools.AddChild(centerAnchor, cardSkillNamePrefab);
		cardSkillNameGo.SetActive(false);
	}
	
	public void OpenCamDebugPanel()
	{
		if(debugCamPanel==null)
		{
			glog.debug("create cam debug");
			debugCamPanel = NGUITools.AddChild(centerAnchor, Resources.Load("Prefabs/Ingame/CamDebugPanel") as GameObject  );
		}
		debugCamPanel.SetActive(true);
	}
	
    //public void CreateGameResultUI()
    //{
    //    if( rebithWindow != null )
    //        if( rebithWindow.activeSelf )
    //            rebithWindow.SetActive(false);

    //    GameObject uiprefab = Resources.Load("Prefabs/UI/Panel_result") as GameObject;
    //    gameResultUI = NGUITools.AddChild(centerAnchor, uiprefab);
    //}
	
	public void CreateSelectRewardUI(bool setActive)
	{
		if( rebithWindow.activeSelf )
			rebithWindow.SetActive(false);

		if(selectRewardUI==null)
		{
			GameObject uiprefab = Resources.Load("Prefabs/UI/Panel_result_SelectItem") as GameObject;
			selectRewardUI = NGUITools.AddChild(centerAnchor, uiprefab);
			resultItemBox[0] = selectRewardUI.transform.FindChild("Panel_result_ItemBox1").gameObject;
			resultItemBox[1] = selectRewardUI.transform.FindChild("Panel_result_ItemBox2").gameObject;
			resultItemBox[2] = selectRewardUI.transform.FindChild("Panel_result_ItemBox3").gameObject;
			resultItemBox[3] = selectRewardUI.transform.FindChild("Panel_result_ItemBox4").gameObject;
		}
		selectRewardUI.SetActive(setActive);
	}
	public void DestroySelectRewardUI()
	{
		Destroy(selectRewardUI);
	}
	
	public void SetMyRankFrame(int index)
	{
		if(index>= panelRank.Length)
			return;
		panelRank[index].transform.FindChild("back_select").gameObject.SetActive(true);
	}
	
	public void SetGameResultRank(int i, BoardPerson person, bool isRetire)
	{
		if(i>= panelRank.Length)
			return;
		string findStr = String.Format("Panel_result_rank{0:0}", i+1);
		panelRank[i] = gameResultUI.transform.FindChild(findStr).FindChild("Panel_rank_E").gameObject;
		panelRank[i].SetActive(true);
		//rankName[i].GetComponent<UILabel>().text = nickname;
		panelRank[i].transform.FindChild("char").gameObject.GetComponent<UISprite>().spriteName = String.Format("Char{0:00}",person.charID);
		panelRank[i].transform.FindChild("Label_name").gameObject.GetComponent<UILabel>().text = person.nickName;
		if(isRetire)
		{
			panelRank[i].transform.FindChild("Label_order").gameObject.SetActive(false);
		}
		else
			panelRank[i].transform.FindChild("Label_order").gameObject.SetActive(true);
	}
	
	public void SetPvpPoint(int i, int pvpPoint, int deltaPvp)
	{
		if(i>= panelRank.Length)
			return;
		glog.debug("pvp point  "+pvpPoint+ "   "+deltaPvp);
		panelRank[i].transform.FindChild("BeforeRank").gameObject.GetComponent<UILabel>().text = pvpPoint.ToString();
		Transform rankPointTrans = panelRank[i].transform.FindChild("Label_RankPoint");
		foreach(Transform child in rankPointTrans)
		{
			if(deltaPvp>=0)
				child.gameObject.GetComponent<UILabel>().text = String.Format("+{0:0}",deltaPvp);
			else
				child.gameObject.GetComponent<UILabel>().text = String.Format("{0:0}",deltaPvp);
		}
		
	}
	
	public void ShowMainHud(bool bShow)
	{
//		foreach( GameObject go in mainHUD) {
//			if(go.name == "TopLeft")
//				continue;
//			NGUITools.SetActive(go, bShow);
//		}
	}
	
	void OnPressUp()
	{
		Camera.main.gameObject.GetComponent<CameraControl>().PressedUIButton(false);
		//glog.debug ("btn up");
	}
	
	public void CallDelayedPressUp()
	{
		StartCoroutine("DelayedPressUp");
	}

	public void PreventCameraTouchForSecond()
	{
		Camera.main.gameObject.GetComponent<CameraControl>().PressedUIButton(true);
		Invoke("OnPressUp",1.0f);
	}

	IEnumerator DelayedPressUp()
	{
		yield return new WaitForSeconds(1.0f);
		OnPressUp();
	}
	
//	public void StartSliderTimer()
//	{
//		StopCoroutine("SliderTimer");
//		StartCoroutine("SliderTimer");		
//	}
	
	public void SetModifyTeamParamMove(int nValue)
	{
//		if(bUseSkill)
//		{
//			bUseSkill = false;
//			Vector3 playerPos = BoardManager.Instance.boardPerson_me.transform.position;
//			float z = skillDiceNumBonus_effect_prefab.transform.position.z;
//			GameObject eff = Instantiate(skillDiceNumBonus_effect_prefab, new Vector3(playerPos.x, playerPos.y+0.4041599f, z), Quaternion.identity  ) as GameObject;
//			eff.transform.parent = BoardManager.Instance.boardPerson_me.transform;
//			Destroy(eff, 3.0f);
//			
//			z = skillDiceNumBonus_prefab.transform.position.z;
//			skillDiceNumBonus = Instantiate(skillDiceNumBonus_prefab, new Vector3(playerPos.x, playerPos.y+0.4041599f, z), Quaternion.identity  ) as GameObject;
//			skillDiceNumBonus.transform.parent = BoardManager.Instance.boardPerson_me.transform;
//			Destroy(skillDiceNumBonus, 5.0f);
//		}
	}
	
	void CreateDiceNum()
	{
		diceNum = Instantiate(diceNum_prefab) as GameObject;
		digit2Go = diceNum.transform.FindChild("digit2").gameObject;
		diceNumMinus = diceNum.transform.FindChild("MoveRollNumMinus").gameObject;
		minusGo = diceNum.transform.FindChild("minus").gameObject;
		diceNum.SetActive(false);
	}
	
	public GameObject ShowDiceNumAbovePerson(BoardPerson person, int nDice, int nAddDice, bool showEffect)//, float offset_y)
	{
		minusGo.SetActive (false);
		diceNumMinus.SetActive(false);
		digit2Go.SetActive (false);
		Vector3 playerPos = person.transform.position;
		playerPos.y += person.overHeadDiceNumOffset;
		
//		if(nAddDice>0)
//		{
//			GameObject eff = EffectManager.Instance.CreateEffectZ(1, playerPos);
//			
//			eff.transform.parent = person.transform;
//			Destroy(eff, 3.0f);
//		}
		
		if(showEffect)
		{
			DiceNumEffect(person,playerPos);		
		}
		
		//if(diceNum)
		//	Destroy(diceNum);


		diceNum.SetActive (true);
		BoardManager.Instance.RestartFSM( diceNum.GetComponent<PlayMakerFSM>() );
		
		//float zz = diceNum_prefab.transform.position.z;
		//diceNum = Instantiate(diceNum_prefab, new Vector3(playerPos.x, playerPos.y, zz), Quaternion.identity  ) as GameObject;

		// 2d tool kit text mesh version
		tk2dSprite numMesh = diceNum.GetComponent<tk2dSprite>();

		if(nDice>9)
		{
			digit2Go.SetActive(true);
			int nDigit1 = nDice % 10;
			int nDigit2 = nDice / 10;
			digit2Go.GetComponent<tk2dSprite>().SetSprite("No_E"+nDigit2.ToString());
			numMesh.SetSprite ("No_E"+nDigit1.ToString());
		}
		else
			numMesh.SetSprite ("No_E"+nDice.ToString());

		nLastDice = nDice;
		//diceNum.GetComponent<UILabel>().text = nDice.ToString();

		diceNum.transform.parent = person.transform;

		Vector3 newPos = diceNum_prefab.transform.position;
		newPos.y += person.overHeadDiceNumOffset;
		if(nDice>9)
			newPos.x += 0.088f;
		diceNum.transform.localPosition = newPos;

		return diceNum;
	}

	public void DecreaseDiceNum(BoardPerson person, int minusValue)
	{
		if(nLastDice==0)
		{
			diceNum.SetActive(false);
			return;
		}
		diceNum.SetActive(true);
		minusGo.SetActive(true);
		diceNumMinus.SetActive(true);
		digit2Go.SetActive (false);
		//BoardManager.Instance.RestartFSM( diceNumMinus.GetComponent<PlayMakerFSM>() );
		tk2dSprite numMinusMesh = diceNumMinus.GetComponent<tk2dSprite>();
		int nAbsoluteValue = -minusValue;
		numMinusMesh.SetSprite("No_E"+nAbsoluteValue.ToString() );

		nLastDice = nLastDice + minusValue;
		if(nLastDice<0)
			nLastDice = 0;
		tk2dSprite numMesh = diceNum.GetComponent<tk2dSprite>();


		if(nLastDice>9)
		{
			digit2Go.SetActive(true);
			int nDigit1 = nLastDice % 10;
			int nDigit2 = nLastDice / 10;
			digit2Go.GetComponent<tk2dSprite>().SetSprite("No_E"+nDigit2.ToString());
			numMesh.SetSprite ("No_E"+nDigit1.ToString());
		}
		else
			numMesh.SetSprite ("No_E"+nLastDice.ToString());

		//numMesh.Commit();
		//if(nLastDice==0)
		//	diceNum.SetActive(false);

		Vector3 newPos = diceNum_prefab.transform.position;
		newPos.y += person.overHeadDiceNumOffset;
		if(nLastDice>9)
			newPos.x += 0.088f;
		diceNum.transform.localPosition = newPos;
	}

	public void HideDiceNum()
	{
		diceNum.SetActive(false);
	}

	public void ShowDiceNum()
	{
		if(nLastDice>0)
		{
			diceNum.SetActive(true);
			diceNumMinus.SetActive(false);
		}
		else
			diceNum.SetActive(false);
	}
	
	public void DiceNumEffect(BoardPerson person, Vector3 pos)
	{
		EffectManager.Instance.PlayEffectZParent(11, pos, person.transform);
		EffectManager.Instance.DisableParticle(11,2.0f);
	}
	
	public void SetSkillAndItem()
	{
		SetHealItemCount( MyInfo.Instance.HPPotion, MyInfo.Instance.ResurrectPotion);
		SetSkillData("Button_Skill1",   SkillManager.Instance.skillID_1 ,0);
		SetSkillData("Button_Skill2",   SkillManager.Instance.skillID_2 ,1);

        SetTempSkillData( MyInfo.Instance.ChanceSkill[0], 0);
        SetTempSkillData( MyInfo.Instance.ChanceSkill[1], 1);

        //SetSkillData("Button_SkillFriend1",   SkillManager.Instance.skillID_3 ,2);
        //SetSkillData("Button_SkillFriend2",   SkillManager.Instance.skillID_4 ,3);		
	}

	public void ShowUIBattleRoll(bool show, DateTime deadLine, DiceShapeType diceShapeType)
	{
		if(show)
		{
			HudManager.Instance.SetTurnTimeCount(BoardManager.Instance.mySID, true);
			BoardManager.Instance.ActivateDiceOverHead( BoardManager.Instance.boardPerson_me, diceShapeType);
			diceType = DiceType.DICE_COMBAT;
			ShowGaugeRoll();
			StartCoroutine("CoGaugeRollTimer", deadLine);

            if (CSceneManager.BuilderIsOn)
            {
                CSceneManager.BuilderStatus = 5;
            }
			curDiceShape = diceShapeType;
		}
		else
		{
			curDiceShape = DiceShapeType.None;
			HideGaugeRoll();
		}
		if(diceShapeType==DiceShapeType.Defender)
			skillItemPanel.SetActive(show);

        	
	}

//	public void HideBattleRoll()
//	{
//		battleRollPanel.SetActive(false);
//	}

	public void ClearBattleRoll()
	{
		Destroy(FX_CountNum_obj);
		StopCoroutine("CoGaugeRollTimer");
		//battleRollPanel.SetActive(false);
		HideGaugeRoll();
	}

	public void ShowUIDirectionRoll(bool show, DateTime deadLine)
	{
		if(show)
		{
			HudManager.Instance.SetTurnTimeCount(BoardManager.Instance.mySID, true);
			diceType = DiceType.DICE_DIRECTION;
			ShowGaugeRoll();
			StartCoroutine("CoGaugeRollTimer", deadLine);
			curDiceShape = DiceShapeType.None;
            if (CSceneManager.BuilderIsOn)
            {
                CSceneManager.BuilderStatus = 4;
            }
        }
		else
		{
			curDiceShape = DiceShapeType.None;
			HideGaugeRoll();
		}
	}

	public void HideGaugeRoll()
	{
//		rollGaugeL.StopGauge(false);
//		rollGaugeR.StopGauge(false);
		if(gaugeRollPanel.activeSelf)
		{
			rollGaugeAnim.Stop();
			gaugeRollPanel.SetActive(false);
		}

		skillItemPanel.SetActive(false);
	}

	void SetRollBtn(bool bClicked)
	{
		if(bClicked)
		{
			rollBtnSprite.spriteName ="RollDiceNew_BtnClick";
			rollBtnSprite.MakePixelPerfect();
			rollBtnSprite.transform.localPosition = new Vector3(-16,-8,0);
		}
		else
		{
			rollBtnSprite.spriteName = "RollDiceNew_Btn1";
			rollBtnSprite.MakePixelPerfect();
			rollBtnSprite.transform.localPosition = Vector3.zero;
		}
	}

	void ShowGaugeRoll()
	{
		SetRollBtn(false);
		gaugeRollPanel.SetActive(true);
//		rollGaugeL.StartGauge();
//		rollGaugeR.StartGauge();
	}

	IEnumerator CoGaugeRollTimer(DateTime deadLine)
	{
		int index = 0;
		
		while (DateTime.UtcNow.Ticks < deadLine.Ticks)
		{
            double totalSeconds = deadLine.Subtract(DateTime.UtcNow).TotalSeconds;
            // 턴 타임 설정
            {
                HudManager.Instance.SetTrunTimeCountNum(BoardManager.Instance.mySID, (float)totalSeconds, true);
            }

            if (totalSeconds < 10)
			{
                totalSeconds = deadLine.Subtract(DateTime.UtcNow).TotalSeconds;
                index = 10 - (int)Math.Ceiling(totalSeconds);
				glog.debug("index -- " + index);
				while (index < 10)
				{
					FX_CountNum_obj = NGUITools.AddChild(centerAnchor, FX_CountNum_obj_prefab);
					FX_CountNum_obj.transform.localPosition = FX_CountNum_obj_prefab.transform.localPosition;
					FX_CountNum_obj.transform.localScale = FX_CountNum_obj_prefab.transform.localScale;
					ParticleSystem ps = FX_CountNum_obj.GetComponent<ParticleSystem>();
					
					ps.renderer.material.mainTexture = textureCount[index];
					//ps.Play();
					index++;
					glog.debug("CoGaugeRollTimer deadLine timer count " + index+"   ");

                    {
                        HudManager.Instance.SetTrunTimeCountNum(BoardManager.Instance.mySID, (float)(10 - index), false);                      
                    }

					yield return new WaitForSeconds(1.0f);	
					Destroy(FX_CountNum_obj);
					//ps.Stop();
				}
			}
			
			yield return new WaitForSeconds(0.2f);
		}
	}

	public void ShowMoveRollButton(bool show, DateTime deadLine)
	{
		if (show)
		{            
			curDiceShape = DiceShapeType.Normal;
			HudManager.Instance.SetTurnTimeCount(BoardManager.Instance.mySID, true);
			//SetSkillAndItem();
			//blackBox.SetActive (true);
			diceType = DiceType.DICE_MOVE;
			ShowRollPanel(true);
			//rollGauge.StartGauge();
			SetRollCount(deadLine);
			Camera.main.gameObject.GetComponent<CameraControl>().SetCameraFocusMe();
			
			//timerSlider.SetActive(true);
			
			
			//			timerSlider.GetComponent<UISlider>().value = 1.0f;
			
			
			//		MainHUDUI.Instance.EnableSkillBtn();
			//		MainHUDUI.Instance.EnableItemBtn();
			//StopCoroutine("SliderTimer");
			//StartCoroutine("SliderTimer");
		}
		else
		{
			curDiceShape = DiceShapeType.None;
			HideRoll();
		}
	}

	public void ShowRollPanel(bool show)
	{
		rollPanel.SetActive(show);
		SetRollBtn(false);
		skillItemPanel.SetActive(show);
	}

	public void HideRoll()
	{
		//if(bDisabledAllBtn)
		//	EnableAllBtnTemporary(true);
		
		//rollGauge.StopGauge(false);
		StopCoroutine("SliderTimer");
		StopCoroutine("SliderTimerOld");
		//FX_CountNum_obj.GetComponent<RollCountTimer>().StopCount();
		Destroy(FX_CountNum_obj);

		if(rollPanel.activeSelf)
		{
			rollGaugeAnim_moveDice.Stop();
			ShowRollPanel(false);
		}

		//blackBox.SetActive(false);
		//StopCoroutine( "SliderTimer");
		bHideRoll = true;
	}

	void OnPressRoll()
	{  
		Camera.main.gameObject.GetComponent<CameraControl>().PressedUIButton(true);
		UIManager.Instance.CallDelayedPressUp();
		SetRollBtn(true);
		if(diceType==DiceType.DICE_MOVE)
			rollGaugeAnim_moveDice.StartGauge();
		else
			rollGaugeAnim.StartGauge();
		SoundManager.Instance.PlaySoundLoop(34);
	}
	
	void OnReleaseRoll()
	{
		SoundManager.Instance.AudioStop();
		if(diceType==DiceType.DICE_MOVE)
		{
			//Camera.main.gameObject.GetComponent<CameraControl>().PressedUIButton(true);
			glog.debug("OnReleaseRoll  "+CNetworkManager.Instance.Connected);
			StartCoroutine("DelayedPressUp");
			
			HideRoll();
			
			float ratio = rollGaugeAnim_moveDice.timeSum;
			nDiceProb = Mathf.CeilToInt (ratio);
			if(nDiceProb==0)
				nDiceProb = 1;
			glog.debug("moveDice press ratio = "+ratio+"   integer="+nDiceProb);
			
			if (CNetworkManager.Instance.Connected)
			{
				PC_CS_ROLL_DICE packet = new PC_CS_ROLL_DICE();
				
				packet.ServerID = BoardManager.Instance.mySID;
				packet.DiceType = (byte)diceType;
				packet.Value = nDiceProb;
				SoundManager.Instance.PlaySound(33);
				CNetworkManager.Instance.SendPacket(packet);
			}
		}
		else
		{
			glog.debug("OnReleaseGaugeRoll");
			Destroy(FX_CountNum_obj);
			StopCoroutine("CoGaugeRollTimer");
			//Camera.main.gameObject.GetComponent<CameraControl>().PressedUIButton(true);
			StartCoroutine("DelayedPressUp");
			
			HideGaugeRoll();
			
			float ratio = rollGaugeAnim.timeSum;
			nDiceProb = Mathf.CeilToInt (ratio);
			if(nDiceProb==0)
				nDiceProb = 1;
			glog.debug("press ratio = "+ratio+"   integer="+nDiceProb);
			
			if (CNetworkManager.Instance.Connected)
			{
				PC_CS_ROLL_DICE packet = new PC_CS_ROLL_DICE();
				
				packet.ServerID = BoardManager.Instance.mySID;
				packet.DiceType = (byte)diceType;
				packet.Value = nDiceProb;
				SoundManager.Instance.PlaySound(33);
				CNetworkManager.Instance.SendPacket(packet);
			}

			if(DiceType.DICE_COMBAT == diceType)
			{
				//byte [] nDiceList = { 3,5};
				//BoardManager.Instance.ShowDiceUI( BoardManager.Instance.boardPerson_me, nDiceList, null, true);
				//BoardManager.Instance.bWaitBattleDiceResult = true;
			}
		}
	}

	IEnumerator SliderTimerOld()
	{
		//		float sum = 0.0f;
		//		timeCountDice=0;
		//		int oldCount = 0;
		//		while(sum < 10)
		//		{
		//			sum += Time.deltaTime;
		//			float ratio = 1 - sum/10.0f;
		//
		//			timeCountDice = (int)sum;
		//			if(oldCount != timeCountDice)
		//			{
		//				ParticleSystem ps = rollPanel.transform.FindChild("FX_CountNum").gameObject.GetComponent<ParticleSystem>();
		//				ps.renderer.material.mainTexture = textureCount[timeCountDice];
		//			}
		//			oldCount = timeCountDice;
		//			yield return null;
		//		}
		int index = 0;
		
		while(index<10 && !bHideRoll)
		{
			FX_CountNum_obj = NGUITools.AddChild(centerAnchor, FX_CountNum_obj_prefab);
			FX_CountNum_obj.transform.localPosition = FX_CountNum_obj_prefab.transform.localPosition;
			FX_CountNum_obj.transform.localScale = FX_CountNum_obj_prefab.transform.localScale;		
			ParticleSystem ps = FX_CountNum_obj.GetComponent<ParticleSystem>();
			
			ps.renderer.material.mainTexture = textureCount[index];
			//ps.Play();
			index++;
			glog.debug("timer count "+index);
			yield return new WaitForSeconds(1.0f);
			Destroy(FX_CountNum_obj);
			//ps.Stop();
		}
		
		
		//		if(timerSlider.activeSelf)
		//			timerSlider.GetComponent<UISlider>().value = 0;
	}
	
	IEnumerator SliderTimer(DateTime deadLine)
	{
        // 여기다라 작업
       
		int index = 0;
		
		while (DateTime.UtcNow.Ticks < deadLine.Ticks && !bHideRoll)
        {
            double totalSeconds = deadLine.Subtract(DateTime.UtcNow).TotalSeconds;
            
            // 턴 타임 설정
            {               
                HudManager.Instance.SetTrunTimeCountNum(BoardManager.Instance.curTurnSID, (float)totalSeconds, true);
            }

            if (totalSeconds < 10)
            {
                index = 10 - (int)Math.Ceiling((totalSeconds));
                glog.debug("index -- " + index);
                while (index < 10 && !bHideRoll)
                {
                    totalSeconds = deadLine.Subtract(DateTime.UtcNow).TotalSeconds;
                    SoundManager.Instance.PlaySound(1);
                    FX_CountNum_obj = NGUITools.AddChild(centerAnchor, FX_CountNum_obj_prefab);
                    FX_CountNum_obj.transform.localPosition = FX_CountNum_obj_prefab.transform.localPosition;
                    FX_CountNum_obj.transform.localScale = FX_CountNum_obj_prefab.transform.localScale;
                    ParticleSystem ps = FX_CountNum_obj.GetComponent<ParticleSystem>();

                    ps.renderer.material.mainTexture = textureCount[index];
                    //ps.Play();
                    index++;
                    glog.debug("deadLine timer count " + index + "   ");

                    {
                        HudManager.Instance.SetTrunTimeCountNum(BoardManager.Instance.curTurnSID, (float)(10 - index), false);
                    }

                    yield return new WaitForSeconds(1.0f);
                    Destroy(FX_CountNum_obj);
                    //ps.Stop();
                }
            }

            yield return new WaitForSeconds(0.2f);
        }
		
		
		//		if(timerSlider.activeSelf)
		//			timerSlider.GetComponent<UISlider>().value = 0;
	}
	
	void SetRollCount()
	{
		//FX_CountNum_obj.SetActive(true);
		//FX_CountNum_obj.GetComponent<RollCountTimer>().StartCount();
		
		bHideRoll = false;
		//ParticleSystem ps = FX_CountNum_obj.GetComponent<ParticleSystem>();
		//ps.Stop();
		StartCoroutine( "SliderTimerOld" );
		
		//	ParticleSystem ps = rollPanel.transform.FindChild("FX_CountNum").gameObject.GetComponent<ParticleSystem>();
		//	ps.Play();
		//	ps.renderer.material.mainTexture = textureCount[timeCountDice];
		
	}
	
	void SetRollCount(DateTime deadLine)
	{        
		bHideRoll = false;
		StartCoroutine("SliderTimer",deadLine);
	}

	public void ShowMoveRollButton(bool show)
	{
		if(show) 
		{
			//SetSkillAndItem();
			//blackBox.SetActive (true);
			//rollPanel.SetActive(true);
            ShowRollPanel(true);
			SetRollCount();
			Camera.main.gameObject.GetComponent<CameraControl>().SetCameraFocusMe();
			
			//timerSlider.SetActive(true);
			
			
//			timerSlider.GetComponent<UISlider>().value = 1.0f;
			
			
	//		MainHUDUI.Instance.EnableSkillBtn();
	//		MainHUDUI.Instance.EnableItemBtn();
			//StopCoroutine("SliderTimer");
			//StartCoroutine("SliderTimer");
		}
		else 
		{
			HideRoll();
		}
	}



	public void GameStart(int num)
	{
		if(num>0 && num<=5)
		{
			SoundManager.Instance.PlaySound(1);
			GameObject go = NGUITools.AddChild(centerAnchor, gameStartNumPrefab);
			ParticleSystem ps = go.GetComponent<ParticleSystem>();
			ps.renderer.material.mainTexture = gameStartTexture[num];
			Destroy(go, 1.0f);
		}
		else if(num==0)
		{
			SoundManager.Instance.PlaySound(ESound.GameStart);
			GameObject go = NGUITools.AddChild(centerAnchor, gameStartPrefab);
			go.transform.localPosition = gameStartPrefab.transform.localPosition;
			Destroy(go,2.0f);
		}
	}

	
	public void SetHealItemCount(int heal, int res)
	{
		glog.debug("SetHealItemCount  "+heal+"   "+res);
		//pressSkillBar.SetItemCount(heal, res);  안쓰는 기능
	//	rollPanel.transform.FindChild("heal").FindChild("num").gameObject.GetComponent<UILabel>().text = heal.ToString();
	//	rollPanel.transform.FindChild("res").FindChild("num").gameObject.GetComponent<UILabel>().text = res.ToString();
		if(heal==0)
		{
			GameObject go = skillItemPanel.transform.FindChild("Button_Item1").gameObject;
			go.transform.FindChild("maskcircle").gameObject.SetActive(true);
			//go.transform.FindChild("FX_RollDice3Skill").gameObject.SetActive(false);
		}
		else
		{
			GameObject go = skillItemPanel.transform.FindChild("Button_Item1").gameObject;
			go.transform.FindChild("maskcircle").gameObject.SetActive(false);
			//go.transform.FindChild("FX_RollDice3Skill").gameObject.SetActive(true);			
		}
		
		if(res==0)
		{
			GameObject go = skillItemPanel.transform.FindChild("Button_Item2").gameObject;
			go.transform.FindChild("maskcircle").gameObject.SetActive(true);
			//go.transform.FindChild("FX_RollDice3Skill").gameObject.SetActive(false);
		}
		else
		{
			GameObject go = skillItemPanel.transform.FindChild("Button_Item2").gameObject;
			go.transform.FindChild("maskcircle").gameObject.SetActive(false);
			//go.transform.FindChild("FX_RollDice3Skill").gameObject.SetActive(true);			
		}
			
	}

	public void EnableAllBtnTemporary(bool bEnable)
	{
		bDisabledAllBtn = !bEnable;
		string [] nameStr = {"Button_Item1", "Button_Item2", "Button_Skill1", "Button_Skill2"};
		for(int i=0; i< nameStr.Length; i++)
		{
			GameObject btn = skillItemPanel.transform.FindChild(nameStr[i]).gameObject;
			btn.transform.FindChild("maskcircle").gameObject.SetActive(!bEnable);
			//btn.transform.FindChild("FX_RollDice3Skill").gameObject.SetActive(bEnable);
			btn.collider.enabled = bEnable;
		}
	}

    public void SetTempSkillData(int skillId, int index)
    {
        if(skillId==0)
		{
            pressSkillBar.SetActivate(false, index + 2);			
			return;
		}
		CSkillData skillData = CSkillDataManager.Instance.FindSkillData(skillId);
		if(skillData==null)
        {
            pressSkillBar.SetActivate(false, index + 2);			
			return;
		}
		
    
		string iconName = skillData.icon_name;
		pressSkillBar.SetActivate(true, index + 2);
		pressSkillBar.SetSkillData(skillData.cost, iconName, index + 2);

        if (IsTempSkillCastOK(index))
            pressSkillBar.SetDisable(false, index + 2);
		else
            pressSkillBar.SetDisable(false, index + 2);
    }
	
	public void SetSkillData(string skillStr, int skillId, int index)
	{
		GameObject btn = skillItemPanel.transform.FindChild(skillStr).gameObject;

		if(skillId==0)
		{
			pressSkillBar.SetActivate(false, index);
			btn.SetActive(false);
			return;
		}
		CSkillData skillData = CSkillDataManager.Instance.FindSkillData(skillId);
		if(skillData==null)
        {            
			pressSkillBar.SetActivate(false, index);
			btn.SetActive(false);
			return;
		}
		else
			btn.SetActive(true);
    
		string iconName = skillData.icon_name;
		pressSkillBar.SetActivate(true, index);
		pressSkillBar.SetSkillData(skillData.cost, iconName, index);
		btn.transform.FindChild("Sprite_SkillIcon").GetComponent<UISprite>().spriteName = iconName;
		btn.GetComponent<UseSkillButton>().skillID = skillId;
		btn.GetComponent<UseSkillButton>().index = index;
					
		if( IsSkillCastOK(skillData, index) )
			DisableSkillIcon(btn, false, index);
		else
			DisableSkillIcon(btn, true, index);
	}
	
	void DisableSkillIcon(GameObject btn, bool bDisable, int index)
	{
		pressSkillBar.SetDisable(bDisable, index);
		btn.transform.FindChild("maskcircle").gameObject.SetActive(bDisable);
		//if(bDisable)
		//	btn.transform.FindChild("FX_RollDice3Skill").gameObject.SetActive(false);	
		//else
		//	btn.transform.FindChild("FX_RollDice3Skill").gameObject.SetActive(true);	
	}

	public void SetTempSkill(int index, int skillId)
	{
        MyInfo.Instance.ChanceSkill[index] = skillId;

		string skillStr = String.Format("Button_TempSkill{0:0}",index+1);
		Transform transSkill = skillItemPanel.transform.FindChild(skillStr);
		if(transSkill!=null)
		{
			GameObject btn = transSkill.gameObject;
			if(skillId==0)
			{
				btn.SetActive(false);
                pressSkillBar.SetActivate(false, index); 
				return;
			}
			CSkillData skillData = CSkillDataManager.Instance.FindSkillData(skillId);
			if(skillData==null)
			{
				btn.SetActive(false);
                pressSkillBar.SetActivate(false, index); 
				return;
			}
			else
				btn.SetActive(true);
			string iconName = skillData.icon_name;
			btn.transform.FindChild("Sprite_SkillIcon").GetComponent<UISprite>().spriteName = iconName;
			btn.GetComponent<UseSkillButton>().skillID = skillId;
			btn.GetComponent<UseSkillButton>().index = index;

            pressSkillBar.SetActivate(true, index + 2);
            pressSkillBar.SetSkillData(skillData.cost, iconName, index + 2);
		}
	}

	public void SetSkillCastableCondition(bool c1, bool c2, bool c3, bool c4)
	{
		is_castable_skill[0] = c1;
		is_castable_skill[1] = c2;
		is_castable_skill[2] = c3;
		is_castable_skill[3] = c4;
	}	

	public void SetTempSkillCastableCondition(int index, bool bCastable)
	{
		if(index<0 || index>=2)
			return;
		is_castable_tempSkill[index] = bCastable;
		glog.debug("temp skill castable  "+index);
		string skillStr = String.Format("Button_TempSkill{0:0}",index+1);
		Transform transSkill = skillItemPanel.transform.FindChild(skillStr);
		if(transSkill!=null)
		{
			GameObject btn = transSkill.gameObject;
			btn.transform.FindChild("maskcircle").gameObject.SetActive(!bCastable);
		}

	}

	public bool IsTempSkillCastOK(int index)
    {        
        if (is_castable_tempSkill[index])
            return true;
        return false;
    }

	
	public bool IsSkillCastOK(CSkillData skillData, int index)
	{
		if( skillData!=null)
		{
			int cost = skillData.cost;
			glog.debug(" IsSkillCastOK   cost="+cost);
		}
		if( is_castable_skill[index] )
			return true;
		return false;
	}
	
	public bool IsSkillCastOK(int skillId, int index)
	{
		CSkillData skillData = CSkillDataManager.Instance.FindSkillData(skillId);
		return IsSkillCastOK(skillData, index);
	}	

	public void UpdateSkillPressBar(int mp)
	{
		pressSkillBar.UpdateSkillPressBar(mp);
	}
	
	public void DisableSkillBar(bool bDisable)
	{
		pressSkillBar.DisableSkillBar(bDisable);
	}
	
	
	public void CanCombatRoll(CPawnWrapper pawnWrapper)
	{
		glog.debug ("uimanager CanCombatRoll");
		m_pawnWrapper = pawnWrapper;
//		battleRollButton.SetActive(true);
		//timerSlider.SetActive(true);
//		timerSlider.GetComponent<UISlider>().value = 1.0f;
		//StopCoroutine("SliderTimer");
		//StartCoroutine("SliderTimer");		
	}

	void OnBattleRoll()
	{
		Camera.main.gameObject.GetComponent<CameraControl>().PressedUIButton(true);
		StartCoroutine("DelayedPressUp");
	//	battleRollButton.SetActive(false);
		//timerSlider.SetActive(false);
		m_pawnWrapper.CombatRoll();
	}



    //void OnConnect()
    //{
    //    Camera.main.gameObject.GetComponent<CameraControl>().PressedUIButton(true);
    //    glog.debug ("connect btn pressed");
    //    CNetworkManager.Instance.ConnectToServer();
    //    StageManagerWrapper.m_Connected = true;		
    //}
	
	void OnCreateAI()
	{
		//Camera.main.gameObject.GetComponent<CameraControl>().PressedUIButton(true);
		if (CNetworkManager.Instance.Connected)
		{
			if (!StageManagerWrapper.bOrdered)
			{
				StageManagerWrapper.MakeAIRunner();
			}
		}		
	}
	
	void OnOrder()
	{
        PC_OP_GAME_START packet = new PC_OP_GAME_START();

        //CNetworkManager.Instance.SendPacket(packet.Protocol, packet.GetParam());
		CNetworkManager.Instance.SendPacket(packet);
	}

	public void EffectDirectionDice(int directionDiceValue)
	{
		if( directionDiceValue <= directionDiceIcons.Count )
		{
			BoardManager.Instance.RestartFSM( directionDiceIcons[directionDiceValue-1].GetComponent<PlayMakerFSM>() );
			GameObject goEff = EffectManager.Instance.CreateEffectParent(13, directionDiceIcons[directionDiceValue-1].transform);
			Destroy(goEff,2.0f);
			for(int i=0; i<4; i++)
			{
				if(selectPathObj[i]!=null && selectPathObj[i].activeSelf)
				{
					if( directionDiceIcons[directionDiceValue-1].transform.parent.gameObject != selectPathObj[i])
					{
						ShowPathIndicatorDiceIcon(selectPathObj[i], false);
						selectPathObj[i].SetActive(false);
						int bid = selectPathObj[i].GetComponent<PathSelectIndicator>().boardId;
						DiscardDestMark(bid);
					}
					else
					{
						PathSelectIndicator indicator = selectPathObj[i].GetComponent<PathSelectIndicator>();
						if(indicator.isRatioGoalMax)
							HudManager.Instance.ShowAIEmotionChat(BoardManager.Instance.curTurnSID, "wayselect_good");
						else if(indicator.isRatioGoalMin)
							HudManager.Instance.ShowAIEmotionChat(BoardManager.Instance.curTurnSID, "wayselect_bad");
					}
				}
			}
		}
	}

	static List<BoardTile> tileToRemoveList = new List<BoardTile>();

	void DiscardDestMark(int bid)
	{
		tileToRemoveList.Clear ();
		foreach(BoardTile tile in BoardManager.Instance.destinationTiles)
		{
			if(BoardManager.Instance.destinationTileBidDic.ContainsKey(tile) )
			{
				if( BoardManager.Instance.destinationTileBidDic[tile].Contains(  PathManager.Instance.GetBoardTile(bid) ) )
				{
					tile.DiscardDestMark();
					tileToRemoveList.Add( tile );
				}
			}
		}

		foreach(BoardTile tile in tileToRemoveList)
		{
			BoardManager.Instance.destinationTiles.Remove(tile);
		}
	}
	
	public PathSelectIndicator CreatePathSelectIndicator(int index, Vector3 pos, int bid, int sid, bool bSelectable, int diceGroup, DateTime selectPathDeadLine)
	{
		if(selectPathObj[index]!=null && selectPathObj[index].activeSelf)
			return selectPathObj[index].GetComponent<PathSelectIndicator>();
		if(!isCreatedPathSelectIndicator && bSelectable)
		{
			StartCoroutine( "CoGaugeRollTimer",selectPathDeadLine );
		}
		isCreatedPathSelectIndicator = true;
		if(selectPathObj[index]==null)
			selectPathObj[index] = Instantiate( pathSelectPrefab[index]) as GameObject;
		else
			selectPathObj[index].SetActive(true);
		pos.z = pathSelectPrefab[index].transform.position.z;
		selectPathObj[index].transform.position = pos;
		PathSelectIndicator indicator = selectPathObj[index].GetComponent<PathSelectIndicator>();
		indicator.isRatioGoalMax=false;
		indicator.isRatioGoalMin=false;
		indicator.boardId = bid;
		indicator.SID = sid;		
		selectPathlabel.SetActive(bSelectable);

		if(bSelectable)
		{
			selectPathObj[index].collider.enabled = true;
			indicator.enabled = true;
			selectPathObj[index].GetComponent<TintLoop>().enabled = true;

			ShowPathIndicatorDiceIcon(selectPathObj[index], false);
		}
		else
		{
			selectPathObj[index].collider.enabled = false;
			indicator.enabled = false;
			selectPathObj[index].GetComponent<TintLoop>().enabled = false;

			ShowPathIndicatorDiceIcon(selectPathObj[index], true);

			if(diceGroup==0)
			{
				diceIcon1.GetComponent<tk2dSprite>().SetSprite("icon_dice_ingame_01");
				diceIcon2.GetComponent<tk2dSprite>().SetSprite("icon_dice_ingame_02");
				diceIcon3.GetComponent<tk2dSprite>().SetSprite("icon_dice_ingame_03");
				directionDiceIcons.Add(diceIcon1);
				directionDiceIcons.Add(diceIcon2);
				directionDiceIcons.Add(diceIcon3);
			}
			else
			{
				diceIcon1.GetComponent<tk2dSprite>().SetSprite("icon_dice_ingame_04");
				diceIcon2.GetComponent<tk2dSprite>().SetSprite("icon_dice_ingame_05");
				diceIcon3.GetComponent<tk2dSprite>().SetSprite("icon_dice_ingame_06");
				directionDiceIcons.Add(diceIcon1);
				directionDiceIcons.Add(diceIcon2);
				directionDiceIcons.Add(diceIcon3);
			}
		}
		return indicator;
		//timerSlider.SetActive(true);
		//timerSlider.GetComponent<UISlider>().value = 1.0f;		
//		StartSliderTimer();
	}
	
	public void DestroyPathSelectUI(int selectedBid)
	{
		if(isCreatedPathSelectIndicator) {

			Destroy(FX_CountNum_obj);
			StopCoroutine("CoGaugeRollTimer");
			directionDiceIcons.Clear();
			//BoardManager.Instance.HideDestMark(0);
			//BoardManager.Instance.HideDestMark(1);
			BoardManager.Instance.isGlowTileForPathSelect = false;
			selectPathlabel.SetActive(false);
			//timerSlider.SetActive(false);
			isCreatedPathSelectIndicator = false;
			for(int i=0; i<4; i++)
			{
				if(selectPathObj[i]!=null && selectPathObj[i].activeSelf)
				{
					if( selectedBid != 0 )
					{
						int bid = selectPathObj[i].GetComponent<PathSelectIndicator>().boardId;
						if( bid != selectedBid)
							DiscardDestMark(bid);
					}

					//Destroy(selectPathObj[i]);
					//selectPathObj[i] = null;
					ShowPathIndicatorDiceIcon(selectPathObj[i] , false);
					selectPathObj[i].SetActive(false);
				}
			}
		}
	}

	void ShowPathIndicatorDiceIcon(GameObject pathObj, bool show)
	{
		diceIcon1 = pathObj.transform.FindChild("diceIcon1").gameObject;
		diceIcon2 = pathObj.transform.FindChild("diceIcon2").gameObject;
		diceIcon3 = pathObj.transform.FindChild("diceIcon3").gameObject;

		diceIcon1.GetComponent<PlayMakerFSM>().enabled = false;
		diceIcon2.GetComponent<PlayMakerFSM>().enabled = false;
		diceIcon3.GetComponent<PlayMakerFSM>().enabled = false;

		diceIcon1.SetActive(false);
		diceIcon2.SetActive(false);
		diceIcon3.SetActive(false);

		diceIcon1.SetActive(show);
		diceIcon2.SetActive(show);
		diceIcon3.SetActive(show);
	}
	
	public void InitReward(bool isPvpRoom)
	{
		//selectedRewardList.Clear ();
		rewardPossibleBoxList.Clear();
		
		CreateSelectRewardUI(false);
		string temp = CStringTableManager.Instance.GetItemById(1656);//1656 보상을 받았습니다
		selectRewardUI.transform.FindChild("SelectRewardText").gameObject.GetComponent<UILabel>().text = temp;
	}
	
//	public void InitReward()
//	{
//		if(exp>0)
//		{
//			AddRewardPossibleBox(0);
//			resultItemBox[0].transform.FindChild("Label_NumExp").gameObject.GetComponent<UILabel>().text = String.Format("x{0:0}",exp);
//		}		
//		int nSelectCount = Math.Min ( rewardPossibleBoxList.Count, maxRewardCount);
		//todo local
//		string temp = CStringTableManager.Instance.GetItemById(1656);//1656 보상을 받았습니다
//		temp = temp.Replace("{0}", nSelectCount.ToString() );
//		selectRewardUI.transform.FindChild("SelectRewardText").gameObject.GetComponent<UILabel>().text = temp;
//	}
	
	
	public void AddRewardItem(int category, int boxId, int count)
	{
		if(category == (int)BoxCategory.EXP)
		{
			AddRewardPossibleBox(0);
			resultItemBox[0].transform.FindChild("Label_NumExp").gameObject.GetComponent<UILabel>().text = String.Format("x{0:0}",count);
		}
		else if(category == (int)BoxCategory.ITEM)
		{
			AddRewardPossibleBox(2);
			string itemname = CItemDataManager.Instance.GetItemData(boxId).name;
			glog.debug("itemname = "+itemname);
			if(boxId == 100)//회복물약
			{
				Transform itemTrans = resultItemBox[2].transform.FindChild("item1");
				foreach(Transform child in itemTrans)
				{
					child.gameObject.GetComponent<UILabel>().text = String.Format("x{0:0}",count);
				}
			}
			else if(boxId == 120)//부활물약
			{
				Transform itemTrans = resultItemBox[2].transform.FindChild("item2");
				foreach(Transform child in itemTrans)
				{
					child.gameObject.GetComponent<UILabel>().text = String.Format("x{0:0}",count);
				}
			}
		}
		else if(category == (int)BoxCategory.COIN)
		{
			AddRewardPossibleBox(1);
			if(boxId == 2)//골드
			{
				resultItemBox[1].transform.FindChild("Label_goldNum").gameObject.GetComponent<UILabel>().text = String.Format("x{0:0}",count);
			}			
		}
		else if(category == (int)BoxCategory.GACHA_POINT)
		{
			AddRewardPossibleBox(3);
			reward_gachaPoint = count;
		}
		else if(category == (int)BoxCategory.UNIT)
		{
			AddRewardPossibleBox(3);
			string unitName = CUnitDataManager.Instance.GetUnitData(boxId).name;
			glog.debug("unitName = "+unitName);
			reward_unitCount = count;
		}
		
	}
	
	public void AddSelectedReward(int category)
	{
		int index = categoryToBoxDic[category];
		BoxCategory boxCat = (BoxCategory)category;
		glog.debug("AddSelectedReward  index="+index+"   cat="+boxCat);
		if(boxCat == BoxCategory.GACHA_POINT)
		{
			resultItemBox[index].transform.FindChild("Label_gacha").gameObject.SetActive(true);
			resultItemBox[index].transform.FindChild("Label_unit").gameObject.SetActive(false);
			resultItemBox[index].transform.FindChild("num").gameObject.GetComponent<UILabel>().text = "0";
		}
		else if(boxCat == BoxCategory.UNIT)
		{
			resultItemBox[index].transform.FindChild("Label_gacha").gameObject.SetActive(false);
			resultItemBox[index].transform.FindChild("Label_unit").gameObject.SetActive(true);
			resultItemBox[index].transform.FindChild("num").gameObject.GetComponent<UILabel>().text = "x0";
		}
		
		if( !rewardPossibleBoxList.Contains(index) )
			return;
	
		
		if(boxCat == BoxCategory.GACHA_POINT)
		{
			resultItemBox[index].transform.FindChild("num").gameObject.GetComponent<UILabel>().text = reward_gachaPoint.ToString();
		}
		else if(boxCat == BoxCategory.UNIT)
		{
			resultItemBox[index].transform.FindChild("num").gameObject.GetComponent<UILabel>().text = reward_unitCount.ToString();
		}
		
		
		//resultItemBox[index]
		resultItemBox[index].transform.FindChild("Sprite_selectbox").gameObject.SetActive(true);
		Transform boxBack = resultItemBox[index].transform.FindChild("boxBack");
		if(boxBack!=null)
			resultItemBox[index].transform.FindChild("boxBack").gameObject.GetComponent<UISprite>().spriteName = "UI_btn02s";
		
		
		
	}
	
	
	void AddRewardPossibleBox(int index)
	{
		if( !rewardPossibleBoxList.Contains(index) )
			rewardPossibleBoxList.Add(index);
	}
	
//	public bool AddSelectedReward(int index)
//	{
//		if( !rewardPossibleBoxList.Contains(index) )
//			return false;
//		
//		if( selectedRewardList.Count >= rewardPossibleBoxList.Count)
//			return false;
//		
//		if( !selectedRewardList.Contains(index) )
//		{
//			selectedRewardList.Add(index);
//			glog.debug("add selectedRewardList "+selectedRewardList.Count);
//			return true;
//		}
//		
//		return false;
//	}
//
//	public bool RemoveSelectedReward(int index)
//	{
//		if( !rewardPossibleBoxList.Contains(index) )
//			return false;
//		
//		if( selectedRewardList.Contains(index) )
//		{
//			selectedRewardList.Remove(index);
//			glog.debug("remove selectedRewardList "+selectedRewardList.Count);
//			return true;
//		}
//		
//		return false;
//	}	
	
	public void SendSelectedReward()
	{
		
	}
	
	public void BlackFocus(bool bActivate)
	{
		if(bActivate && blackFocus.alpha>0)
			return;
		if(!bActivate && blackFocus.alpha==0)
			return;
		
		StartCoroutine(CoBlackFocus(bActivate));
	}
	
	IEnumerator CoBlackFocus(bool bActivate)
	{
		if(bActivate)
		{
			blackFocus.gameObject.SetActive(true);
			while(blackFocus.alpha<1)
			{
				blackFocus.alpha += Time.deltaTime * 2.0f;
				if(blackFocus.alpha>1)
					blackFocus.alpha=1;
				yield return null;
			}
		}
		else
		{
			while(blackFocus.alpha>0)
			{
				blackFocus.alpha -= Time.deltaTime * 2.0f;
				if(blackFocus.alpha<0)
					blackFocus.alpha=0;
				yield return null;
			}
			blackFocus.gameObject.SetActive(false);
		}
	}
	
	
	public void SkillNameShow(int skillId)
	{
		if( !skillNameDic.ContainsKey(skillId) )
		{
			CSkillData skillData =  CSkillDataManager.Instance.FindSkillData(skillId);
			if(skillData==null)
				return;
			//if( HudManager.Instance.IsLocalKorean() )
			if( !string.IsNullOrEmpty(skillData.name_string) )
			{
				string strText = CStringTableManager.Instance.GetItemByName(skillData.name_string);
				if( !string.IsNullOrEmpty(strText) )
					skillNameDic.Add (skillId, strText);
			}
		}
		if( skillNameDic.ContainsKey(skillId) )
		{
			skillNameShowGo.SetActive(true);
			skillNameShowGo.transform.localPosition = skillNameShowPrefab.transform.localPosition;
			skillNameShowGo.GetComponent<UILabel>().text = skillNameDic[skillId];
		}
	}
	
	public void CardSkillNameShow(string str)
	{
		cardSkillNameGo.SetActive(true);
		cardSkillNameGo.transform.localScale = cardSkillNamePrefab.transform.localScale;
		cardSkillNameGo.GetComponent<UILabel>().text = str;
	}
	
	public void CardSkillNameShow(UIType uiType)
	{
		CardSkillNameShow( uiString[uiType] );
	}
	
	//popup 추가
    Popup_Goal Popup_GoalSc = null;
	public void ShowFinishPopUp(string nickName, GameOverType gameOverType)
	{
		string str = "";
		if(gameOverType== GameOverType.OCCUPY_THE_GOAL)
			str = CStringTableManager.Instance.GetItemById(1678).Replace("{0}",nickName);  // goal reach
		else if(gameOverType== GameOverType.FINISH_LAP)
			str = CStringTableManager.Instance.GetItemById(1678).Replace("{0}",nickName);  // finish lap
		else
			str = CStringTableManager.Instance.GetItemById(1679).Replace("{0}",nickName);  // final survival
		
        //popup 추가
        Popup_GoalSc = PopupManager.PopupPush(PopupKind.Popup_Goal) as Popup_Goal;
        Popup_GoalSc.SetPopupWithStr(str);
	}
	
	public void ResetFinishPopUp()
	{
        if(Popup_GoalSc != null)
            PopupManager.PopupPop(Popup_GoalSc.gameObject);
	}
	
	public void ShowSkillInfo(string str, bool isGood)
	{
		//Destroy(goShowSkillInfo);
		if(goShowSkillInfo==null)
			goShowSkillInfo = NGUITools.AddChild(bottomAnchor, skillInfoTextPrefab);
		goShowSkillInfo.SetActive(true);
		BoardManager.Instance.RestartFSM( goShowSkillInfo.GetComponent<PlayMakerFSM>() );
		UILabel lbl = goShowSkillInfo.GetComponentInChildren<UILabel>();
		lbl.text = str;
		if(isGood)
			lbl.color = new Color(224/255.0f, 146/255.0f, 4/255.0f, 1);
		else
			lbl.color = new Color(216/255.0f, 79/255.0f, 79/255.0f, 1);

		goShowSkillInfo.transform.localPosition = skillInfoTextPrefab.transform.position;
	}

    MiniMapWindow miniMapWindow;
    public void OnClickMiniMapButton()
    {
        if (miniMapWindow == null)
        {
            miniMapWindow = LTPrefabManager.InstantiateC(PrefabTypes.Panel_MiniMap) as MiniMapWindow;
			if(miniMapWindow==null)
			{
				Debug.LogError("miniMapWindow null");
				return;
			}
            miniMapWindow.transform.parent = centerAnchor.transform;
            miniMapWindow.transform.localScale = Vector3.one;
            miniMapWindow.transform.localPosition = Vector3.zero;
			miniMapWindow.windowMode = MINIMAPWINDOWMODE.FULL;
			miniMapWindow.uiManager = this;
			miniMapBar.transform.parent = topAnchor.transform.parent;
        }
        else
        {
            miniMapWindow.Show();
			miniMapBar.transform.parent = topAnchor.transform.parent;
        }

		Debug.LogError(miniMapBar.GetComponent<UIPanel>().depth);
		miniMapBar.GetComponent<UIPanel>().depth = 41;
		Debug.LogError(miniMapBar.GetComponent<UIPanel>().depth);
//		Vector3 tempPos = miniMapBar.transform.localPosition;
//		tempPos.y = 290f;
//		miniMapBar.transform.localPosition = tempPos;
    }

	GameObject rebithWindow;
	GameObject notEnoughCostWindow;
	public void ShowRebirthWindow()
	{
		PreventCameraTouchForSecond();
		CMapData mapdata = CMapDataManager.Instance.GetMapData(CSceneManager.m_mapName);
		if( rebithWindow == null )
		{
			rebithWindow = LTPrefabManager.InstantiatePrefab(PrefabTypes.Panel_ContinuePopUp_1, Vector3.zero, Quaternion.identity);
			Transform trans = rebithWindow.transform;
			trans.parent = centerAnchor.transform;
			trans.localPosition = Vector3.zero;
			trans.localScale = Vector3.one;
			trans.FindChild("window").FindChild("Btn_Rebirth").GetComponent<UIButtonMessage>().target = gameObject;
			trans.FindChild("window").FindChild("Btn_Cancel").GetComponent<UIButtonMessage>().target = gameObject;
			trans.FindChild("window").FindChild("Label2").GetComponent<UILabel>().text = trans.FindChild("window").FindChild("Label2").GetComponent<UILabel>().text.Replace("{0}", mapdata.continue_cost.ToString());
		}
		else
		{
			rebithWindow.transform.FindChild("window").gameObject.SetActive(true);
			rebithWindow.SetActive(true);
		}
		
		if( isCountDownShowing && rebithWindow != null )
			ShowCountDown(rebithWindow);

        tempRebirthButton.SetActive(false);
	}

	public void HideRebirthWindow()
	{
		if( rebithWindow != null )
			rebithWindow.SetActive(false);
	}

	void OnClickedReBirthButton()
	{
		CMapData mapdata = CMapDataManager.Instance.GetMapData(CSceneManager.m_mapName);
		if( MyInfo.Instance.Diamond >= mapdata.continue_cost )
		{
			CSceneManager.ContinuePlay();
			rebithWindow.transform.FindChild("window").gameObject.SetActive(false);
			if( !tempRebirthButton.activeSelf )
				tempRebirthButton.SetActive(false);
		}
		else
		{
			rebithWindow.SetActive(false);
			ShowNotEnoughDiamondWindow(true);
		}
	}

	public ChooseGameOrderWindow chooseGameOrderWindow;
	public void ShowChooseGameOrderWindow()
	{
		if( chooseGameOrderWindow == null )
		{
			chooseGameOrderWindow = LTPrefabManager.InstantiateC(PrefabTypes.Panel_ChooseGameOrder, Vector3.zero, Quaternion.identity) as ChooseGameOrderWindow;
			Transform trans = chooseGameOrderWindow.transform;
			trans.parent = centerAnchor.transform;
			trans.localPosition = Vector3.zero;
			trans.localScale = Vector3.one;
		}
		else
		{
			chooseGameOrderWindow.transform.FindChild("window").gameObject.SetActive(true);
			chooseGameOrderWindow.gameObject.SetActive(true);
		}
	}

	public void SetCountDownForChooseGameOrder(int sec)
	{
		if(chooseGameOrderWindow!=null)
			chooseGameOrderWindow.SetCountDownSlider(sec);
	}

	public void ShowNotEnoughDiamondWindow(bool isContinue)
	{
		CMapData mapdata = CMapDataManager.Instance.GetMapData(CSceneManager.m_mapName);
		if( notEnoughCostWindow == null )
		{
			notEnoughCostWindow = LTPrefabManager.InstantiatePrefab(PrefabTypes.Panel_ContinuePopUp_2, Vector3.zero, Quaternion.identity);
			Transform trans = notEnoughCostWindow.transform;
			trans.parent = centerAnchor.transform;
			trans.localPosition = Vector3.zero;
			trans.localScale = Vector3.one;
			trans.FindChild("Btn_Cancel").GetComponent<UIButtonMessage>().target = gameObject;
			if( isContinue )
				trans.FindChild("Label_Desc").GetComponent<UILabel>().text = trans.FindChild("Label_Desc").GetComponent<UILabel>().text.Replace("{0}", (mapdata.continue_cost - MyInfo.Instance.Diamond).ToString());
			else
				trans.FindChild("Label_Desc").GetComponent<UILabel>().text = trans.FindChild("Label_Desc").GetComponent<UILabel>().text.Replace("{0}", "1");
		}
		else
		{
			if( GameObject.Find("Panel_RandomBox") != null )
				UICamera.currentCamera.depth = 2;

			notEnoughCostWindow.SetActive(true);
		}
	}

	void OnClickedReBirthCancelButton()
	{
		PreventCameraTouchForSecond();
		if( notEnoughCostWindow != null )
		{
			UICamera.currentCamera.depth = 0;
			notEnoughCostWindow.SetActive(false);
		}
		if(	rebithWindow != null )
			rebithWindow.SetActive(false);


		if( !tempRebirthButton.activeSelf && randomBoxSelectWindow == null)
			tempRebirthButton.SetActive(true);
	}

	void OnClickedExitGameButton()
	{
		PreventCameraTouchForSecond();
		CSceneManager.manager.SendGiveUp();
	}

	RandomBoxSelectWindow randomBoxSelectWindow;
	public void ShowSelectRandomBoxWindow(int[] boxCategoryList, int[] boxCIdList, int[] amountList, int boxCount, int chooseCount)
	{
		randomBoxSelectWindow = LTPrefabManager.InstantiateC(PrefabTypes.Panel_RandomBox, Vector3.zero, Quaternion.identity) as RandomBoxSelectWindow;
		Transform trans = randomBoxSelectWindow.transform;
		trans.parent = centerAnchor.transform;
		trans.localPosition = Vector3.zero;
		trans.localScale = Vector3.one;
		randomBoxSelectWindow.SetWindowInfos(boxCategoryList, boxCIdList, amountList, boxCount, chooseCount);
	}

	EmoticonChatWindow _emoticonWindow;
    bool isPopEmoticonBox = false;
	public void OnClickedEmoticonChatButton()
	{
        if (_emoticonWindow == null)
        {
            GameObject preFab = Resources.Load("Prefabs/UI/Panel_Emoticon") as GameObject;
            GameObject obj = Instantiate(preFab) as GameObject;
            _emoticonWindow = obj.GetComponent<EmoticonChatWindow>();
            //_emoticonWindow = LTPrefabManager.InstantiateC(PrefabTypes.Panel_Emoticon, Vector3.zero, Quaternion.identity) as EmoticonChatWindow;
            Transform trans = _emoticonWindow.transform;
            trans.parent = centerAnchor.transform;
            trans.localPosition = Vector3.zero;
            trans.localScale = Vector3.one;
            Debug.LogError(_emoticonWindow.transform.parent.name);
        }
        isPopEmoticonBox = !isPopEmoticonBox;
        _emoticonWindow.gameObject.SetActive(isPopEmoticonBox);
	}

    //public void HideEmoticomWindow()
    //{
    //    if( _emoticonWindow != null )
    //        _emoticonWindow.gameObject.SetActive(false);
    //}

	public void ShowCountDown(GameObject window)
	{
		Debug.LogError("ShowGameContinueCountDown");
		StartCoroutine("Co_ShowGameContinueCountDown", window);
	}

	public bool isCountDownShowing = false;
	public DateTime deadLine;
	IEnumerator Co_ShowGameContinueCountDown(GameObject window)
	{
		int seconds = 0;
		window.transform.FindChild("CountDown").gameObject.SetActive(true);
		while (DateTime.UtcNow.Ticks < deadLine.Ticks)
		{
			seconds = (int)Math.Ceiling((deadLine.Subtract(DateTime.UtcNow).TotalSeconds));
			if( seconds <= 10 )
			{
				Debug.LogError(seconds);
				window.transform.FindChild("CountDown").gameObject.GetComponent<UILabel>().text = seconds.ToString();
				if (seconds <= 0)
				{
					window.SetActive(false);
					break;
				}
				yield return new WaitForSeconds(1.0f);
			}
			yield return new WaitForSeconds(0.2f);
		}

		if( window.activeSelf )
			window.SetActive(false);

		isCountDownShowing = false;
	}

	GameRewardResultWindow gameRewardResultWindow;
	public void ShowGameRewardResultWindow(List<int> rewardPointList, List<int>rewardPointDeltaList, List<int> rewardItemList, List<int> rewardItemDeltaList, int unitCardCount, int[] unitCardIdList)
	{
		if( gameRewardResultWindow == null )
		{
			gameRewardResultWindow = LTPrefabManager.InstantiateC(PrefabTypes.Panel_GameRewardResult, Vector3.zero, Quaternion.identity) as GameRewardResultWindow;
			Transform trans = gameRewardResultWindow.transform;
			trans.parent = centerAnchor.transform;
			trans.localPosition = Vector3.zero;
			trans.localScale = Vector3.one;
		}
		
		gameRewardResultWindow.SetWindowInfo(rewardPointList, rewardPointDeltaList, rewardItemList, rewardItemDeltaList, unitCardCount, unitCardIdList);
	}

	public void ChangeStatusBoardText(string body)
	{
		statusBoardText.text = body;
		int width = statusBoardText.width;
		float destXPos = 200 - width;

		TweenPosition twPosition = new TweenPosition();
		twPosition.from = statusBoardText.transform.localPosition;
		twPosition.to = new Vector3(destXPos, 0f, 0f);
		twPosition.delay = 0f;
		twPosition.duration = 3f;
		twPosition.PlayForward();
	}

	public void OpenTestDiceColorPanel()
	{
		if(testDiceColorPanel==null)
			testDiceColorPanel = NGUITools.AddChild( centerAnchor, Resources.Load("Prefabs/Ingame/UI/SelectDiceColor") as GameObject );
		testDiceColorPanel.SetActive(true);
	}

	public void TestShowAchievement(int achievementID)
	{
		CAchievementData adata = CAchievementDataManager.Instance.GetAchievementData(achievementID);
        if (adata != null)
        {
           // Debug.LogError("heeso---------------------------------- TestShowAchievement  adata != null " + adata);
            AchievementCell.AddAchievement(adata);
        }
        else
        {
           // Debug.LogError("heeso---------------------------------- TestShowAchievement  adata == null");
        }
    }

	// Update is called once per frame
	void Update () {
		if (CNetworkManager.Instance.Connected && !CSceneManager.isReplay)
		{
			if(!isConnectedCheck) {
				isConnectedCheck = true;
				//connectButton.SetActive(false);
				//createPawnPanel.SetActive(true);
				bCreatePawnPanel = true;
			}
			
			
//			if(StageManagerWrapper.bOrdered) {
//				orderButtonText.GetComponent<tk2dTextMesh>().text = "Start";
//				orderButtonText.GetComponent<tk2dTextMesh>().Commit();
//				pcButton.SetActive(false);
//				aiButton.SetActive(false);
//			}

            if (StageManagerWrapper.Instance.Status == GameStatus.GS_CREATEPAWN || StageManagerWrapper.Instance.Status == GameStatus.GS_UNSEALED)
            {
                //CPawn tmpPawn = StageManagerWrapper.Instance.FindPawn(StageManagerWrapper.m_MySID);
                //if (tmpPawn != null && tmpPawn.ReadyStatus != ReadyStatus.RS_READY)
                //{
                //    orderButtonText.GetComponent<tk2dTextMesh>().text = "Ready";
                //    orderButtonText.GetComponent<tk2dTextMesh>().Commit();
                //}
                //else if (tmpPawn != null && tmpPawn.ReadyStatus == ReadyStatus.RS_READY)
                //{
                //    orderButtonText.GetComponent<tk2dTextMesh>().text = "Cancel";
                //    orderButtonText.GetComponent<tk2dTextMesh>().Commit();
                //}
            }

//            if (StageManagerWrapper.Instance.Status == GameStatus.GS_CREATEPAWN)
//            {
//                pcButton.SetActive(false);
//                aiButton.SetActive(true);
//            }
//            else
//            {
//                pcButton.SetActive(false);
//                aiButton.SetActive(false);
//            }

            if (bCreatePawnPanel)//createPawnPanel.active)
            {
                if (StageManagerWrapper.Instance.Status == GameStatus.GS_PLAYING)
                {
					bCreatePawnPanel = false;
                    //createPawnPanel.SetActive(false);
                }
            }
			//pcButton.SetActive(true);
			//aiButton.SetActive(true);
			//orderButton.SetActive(true);
			//connectButton.SetActive(false);
		}
		else {
			//pcButton.SetActive(false);
			//aiButton.SetActive(false);
			//orderButton.SetActive(false);
			//connectButton.SetActive(true);
		}
	}
}
